package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.MessageDao;
import model.Message;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author tongchen
 * @create 2023-04-02 10:28
 * 需要考虑的内容：①http协议和版本号②方法类型post③接口
 */
@WebServlet("/message")
public class ServletTest extends HttpServlet {

    MessageDao messageDao=new MessageDao();
    ObjectMapper objectMapper = new ObjectMapper();


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //确定两者数据传输过程中的数据格式和编码集
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //接收数据（objectMapper）
        //测试getParameter()
        System.out.println(req.getParameter("sender")+"这是测试的....");
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //创建集合存储数据
        int result = messageDao.insert(message);
        System.out.println(message);
        //将数据写回前端
//        String s = objectMapper.writeValueAsString(insert);
        //在控制台中打印数据
        if (result != 1) {
            // 设置响应内容
            resp.getWriter().write("{\"code\": -1}");
        } else {
            // 设置响应内容
            resp.getWriter().write("{\"code\": 200}");
        }



    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        //获取数据
        List<Message> messages = messageDao.selectAll();
        //将数据格式化
        String s = objectMapper.writeValueAsString(messages);
        resp.getWriter().write(s);

    }
}
